<template>
    <div class="form">
        <div class="formTip">
            <van-image :src="img"></van-image>
            <p>我们将以短信的形式发送验证码至您的手机</p>
        </div>
        <van-field
            v-model="telCode"
            center
            clearable
            label="短信验证码"
            placeholder="请输入短信验证码"
        >
            <template #button>
                <van-button :disabled="time < 10" size="small" type="primary" @click="send" >{{text}}</van-button>
            </template>
        </van-field>
        <div class="my-button">
            <van-button :disabled="flag" color="#ff6666" block round @click="checkCodeFn">下一步</van-button>
        </div>
    </div>
</template>

<script>
import Vue from 'vue';
import { Field , Button , Image as VanImage , Toast } from 'vant';
import { DosendmsgCode , DocheckCode} from '../../api/user'

Vue.use(Field);
Vue.use(Button)
Vue.use(VanImage)

export default {
    data(){
        return{
            text: '发送验证码',
            timer: null , // 计时器
            time: 10,
            telCode:'',
            img:'',
        }
    },
    methods:{
        send(){
            DosendmsgCode({tel:localStorage.getItem('tel')}).then(res =>{
                Toast('短信验证码已发送至您的手机，请注意查收')
                console.log(res);
            })

            this.timer = setInterval(()=>{
                this.text = this.time + 's后重新发送'
                this.time --
                if(this.time === -1){
                    clearInterval(this.timer)
                    this.time = 10
                    this.text = '发送验证码'
                }
            } , 1000)
        },
        checkCodeFn(){
            DocheckCode({tel:localStorage.getItem('tel') , telcode:this.telCode}).then(res => {
                console.log(res);
                if (res.data.code === '10007') {
                    Toast('验证码输入错误')
                } else {
                    this.$router.push('/register/step3')
                }
            })
        }
    },
    computed: {
        flag () {
            if (this.telCode.length < 4) {
                return true
            } else {
                return false
            }
        }
    },
}
</script>

<style lang="stylus" scoped>
.form
    .formTip
        display: flex
        height: 200px
        flex-direction: column
        justify-content: center
        align-items: center
    .my-button
        margin-top: 30px
</style>